package ducpham.rogueconsole.mark2;

import java.awt.Color;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Observable;

public class RKeyListener extends Observable implements KeyListener {

	private static final int DELAY_MARK = 5;

	RConsole console;
	Point current = null;
	Point previous = null;
	int xMod = 0;
	int yMod = 0;
	int delay = 0;

	public RKeyListener(RConsole console) {
		this.console = console;
		console.addKeyListener(this);
		current = new Point(console.getCols() / 2, console.getRows() / 2);
		previous = new Point();
		console.setColor(current.x, current.y, new Color(0xfdf6e3));
	}

	@Override
	public void keyPressed(KeyEvent e) {
		int temp = delay;
		delay = 0;
		int modSpeed;
		int modifiers = e.getModifiers();
		if ((modifiers & KeyEvent.CTRL_MASK) != 0) {
			modSpeed = 2;
		} else
			modSpeed = 1;
		switch (e.getKeyCode()) {
		case KeyEvent.VK_LEFT:
			xMod = -modSpeed;
			break;
		case KeyEvent.VK_RIGHT:
			xMod = modSpeed;
			break;
		case KeyEvent.VK_UP:
			yMod = -modSpeed;
			break;
		case KeyEvent.VK_DOWN:
			yMod = modSpeed;
			break;
		default:
			delay = temp;
			break;
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		switch (e.getKeyCode()) {
		case KeyEvent.VK_LEFT:
			if (xMod < 0)
				xMod = 0;
			break;
		case KeyEvent.VK_RIGHT:
			if (xMod > 0)
				xMod = 0;
			break;
		case KeyEvent.VK_UP:
			if (yMod < 0)
				yMod = 0;
			break;
		case KeyEvent.VK_DOWN:
			if (yMod > 0)
				yMod = 0;
			break;
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
	}

	public void moveCursor() {
		if (xMod == 0 && yMod == 0) {
			delay = 0;
			return;
		}
		if (0 < delay && delay < DELAY_MARK) {
			delay++;
			return;
		}
		previous = new Point(current);
		current.x += xMod;
		current.y += yMod;
		try {
			console.setColor(previous.x, previous.y, new Color(0x002b36));
			console.setColor(current.x, current.y, new Color(0xfdf6e3));
		} catch (NullPointerException npe) {
		}
		delay++;
	}
}
